package com.atguigu.charset;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.*;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;

/**
 * className: CharsetDemo
 * description:
 * date: 2023/3/10 0010-15:54
 * <p>
 * project: nio
 * package: com.atguigu.charset
 * email: 1085844536@qq.com
 * version:
 *
 * @author WangGuojian
 */
public class CharsetDemo {

    public static void main(String[] args) throws CharacterCodingException {
        // 1.获取 charset 对象
        Charset charset = StandardCharsets.UTF_8;

        // 2.获取编码器对象
        CharsetEncoder charsetEncoder = charset.newEncoder();

        // 3.创建缓冲区
        CharBuffer charBuffer = CharBuffer.allocate(1024);
        charBuffer.put("atguigu尚硅谷");
        charBuffer.flip();

        // 4.编码
        ByteBuffer byteBuffer = charsetEncoder.encode(charBuffer);
        System.out.println("编码之后结果：");
        for (int i = 0; i < byteBuffer.limit(); i++) {
            System.out.println(byteBuffer.get());
        }

        // 5.获取解码器对象
        byteBuffer.flip();
        CharsetDecoder charsetDecoder = charset.newDecoder();

        // 6.解码
        CharBuffer charBuffer1 = charsetDecoder.decode(byteBuffer);
        System.out.println("解码之后结果：");
        System.out.println(charBuffer1);

        // 7.使用 GBK 解码
        Charset charset1 = Charset.forName("GBK");
        byteBuffer.flip();
        CharBuffer charBuffer2 = charset1.decode(byteBuffer);
        System.out.println("使用其他编码进行解码：");
        System.out.println(charBuffer2);

        // 8.获取 Charset 所支持的字符编码
        SortedMap<String, Charset> map = Charset.availableCharsets();
        Set<Map.Entry<String, Charset>> set = map.entrySet();
        for (Map.Entry<String, Charset> entry : set) {
            System.out.println(entry.getKey() + "=" + entry.getValue());
        }
    }
}
